//
//  CZComposeView.swift
//  WHWeiBo01
//
//  Created by whitcast on 16/7/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import pop

class CZComposeView: UIView {
    //  存储目标控制器
    private var target: UIViewController?
    //  存储创建的composeButton
    private lazy var composeButtonArray = [CZComposeMenuButton]()
    
    // MARK: --懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  代码已经抽取到UIImage+Extension里面
//    //  截取屏幕快照
//    private func getScreenshot() -> UIImage {
//        //  获取主window
//        let window = UIApplication.sharedApplication().keyWindow!
//        // 开启图片上下文
//        //  截取的不是高清图片
////        UIGraphicsBeginImageContext(window.size)
//        // scale 0 表示屏幕的真是分辨率, 其他数字表示  数字*点的大小
//        UIGraphicsBeginImageContextWithOptions(window.size, false, 0)
//        
//        //  把window内容渲染到图片上下文中 -Hierarchy层次的意思,性能要比drawRect要高
//        window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: false)
//        //  从上下文中获取图片
//        let image = UIGraphicsGetImageFromCurrentImageContext()
//        
//        
//        // 关闭图片上下文
//        UIGraphicsEndImageContext()
//        return image
//        
//    }
    
    
    
    func show(target: UIViewController) {
        self.target = target
        
        //  获取最上面的一个window
//        let window = UIApplication.sharedApplication().windows.last!
        

       // window.addSubview(self)
        
        target.view.addSubview(self)
        
        /**
        开启动画
        */
        
        for (i, value) in composeButtonArray.enumerate() {
            
            startAnimation(value, i: i, isUp: true)
        }
            
    }
    
    
    
    
    //  添加控件设置约束
    private func setupUI() {
    
        backgroundColor = RandomColor()
        //  设置视图大小
        self.frame.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        //  添加控件
        addSubview(bgImageView)
        //  设置约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        
        addChildButton()

        
    }
    
    
    //  读取plist文件
    private func loadComposePlist() -> [CZComposeMenu] {
    
        //  获取plist文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        //  读取plist文件
        let composeDicArray = NSArray(contentsOfFile: path)!
        
        
        var tempArray = [CZComposeMenu]()
        for dic in composeDicArray {
        
            let composeMenu = CZComposeMenu(dic: dic as! [String : AnyObject])
            tempArray.append(composeMenu)
        
        }
        
        
        return tempArray
        
    }
    
    
    
    //  添加6个子按钮
    private func addChildButton() {
        //  按钮的宽度
        let buttonWidth: CGFloat = 80
        //  按钮的高度
        let buttonHeight: CGFloat = 110
        //  按钮直接的间距
        let itemMargin: CGFloat = (width - 3 * buttonWidth) / 4
        //  获取plist里面的数据
        let composeMenuArray = loadComposePlist()
        
        for (i, value) in composeMenuArray.enumerate() {
            
            let button = CZComposeMenuButton()
            //  设置模型
            button.composeMenu = value
            //  添加点击事件
            button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            //  计算列的索引
            let colIndex = i % 3
            //  计算行的索引
            let rowIndex = i / 3
            
            //  计算x坐标
            button.x = buttonWidth * CGFloat(colIndex) + CGFloat(colIndex + 1) * itemMargin
            
            //  计算y坐标
            button.y = buttonHeight * CGFloat(rowIndex) + CGFloat(rowIndex) * itemMargin + ScreenHeight
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.setTitle(value.title!, forState: .Normal)
            
            
            addSubview(button)
            
            //  添加到指定数组
            composeButtonArray.append(button)

        
        }
        
        
    }
    //  开启pop动画
    private func startAnimation(value: UIButton, i: Int, isUp: Bool) {
    
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //  动画执行目的地
        
        let y = isUp ? value.centerY - 350 : value.centerY + 350
        //  动画执行目的地
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))
        //  设置弹簧效果 抖动幅度访问 range [0, 20]
        animation.springBounciness = 8
        //  抖动的初始速度
        animation.springSpeed = 10
        //  开始动画时间
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
        //  执行动画
        value.pop_addAnimation(animation, forKey: nil)

    
    }
    
    // MARK:    - 点击按钮事件
    @objc private func buttonAction(btn: CZComposeMenuButton) {
    
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.composeButtonArray {
                value.alpha = 0.2
                if value == btn {
                    //  点击放大
                    value.transform = CGAffineTransformMakeScale(3, 3)
                    
                    
                } else {
                    //  其它按钮缩小
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
                
            }
            
            
            
            
            
            }) { (_) -> Void in
                
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    for value in self.composeButtonArray {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    }, completion: { (_) -> Void in
                        
                        let classType = NSClassFromString(btn.composeMenu!.className!) as! UIViewController.Type
                        
                        
                        //  创建指定对象
                        let vc = classType.init()
                        
                        //  创建导航控制器
                        let nav = UINavigationController(rootViewController: vc)
                      
                        self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                        

                        
                        
                        
                        
                        
                        
                })
                
        }
        
        
        
        
        
        
        
        
        
    }
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //  数组反转
        for (i, value) in composeButtonArray.reverse().enumerate() {
            startAnimation(value, i: i, isUp: false)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            //  结束刷新
            self.removeFromSuperview()
        })
        
    }
    

}
